package com.coderg.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coderg.gmall.common.execption.GmallException;
import com.coderg.gmall.model.product.*;
import com.coderg.gmall.product.mapper.*;
import com.coderg.gmall.product.service.ManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author CoderG
 * @Date 2025/5/18 22:21
 **/
@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    SpuInfoMapper spuInfoMapper;
    @Autowired
    BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    SpuImageMapper spuImageMapper;
    @Autowired
    SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    SkuInfoMapper skuInfoMapper;
    @Autowired
    SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    SkuImageMapper skuImageMapper;
    @Autowired
    SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    /**
     * 查找全部一级目录
     *
     * @return
     */
    @Override
    public List<BaseCategory1> findCategory1() {

        return baseCategory1Mapper.selectList(null);

    }

    /**
     * 通过一级目录id查找二级目录
     *
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseCategory2> findCategory2(Long category1Id) {
        if (StringUtils.isEmpty(category1Id)) {
            throw new GmallException("参数错误", 200);
        }

        LambdaQueryWrapper<BaseCategory2> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseCategory2::getCategory1Id, category1Id);
        return baseCategory2Mapper.selectList(wrapper);
    }

    /**
     * 通过er级目录id查找san级目录
     *
     * @param category2Id
     * @return
     */
    @Override
    public List<BaseCategory3> findCategory3(Long category2Id) {
        if (StringUtils.isEmpty(category2Id)) {
            throw new GmallException("参数错误", 200);
        }
        LambdaQueryWrapper<BaseCategory3> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseCategory3::getCategory2Id, category2Id);
        return baseCategory3Mapper.selectList(wrapper);

    }

    /**
     * 保存平台属性和值
     *
     * @param listMap
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfoAndValue(Map<String, Object> listMap) {
        String attrName = (String) listMap.get("attrName");
        if (StringUtils.isEmpty(attrName)) {
            throw new GmallException("参数错误", 200);
        }
        Long categoryId = new Long((Integer) listMap.get("categoryId"));
        List attrValueList = (List) listMap.get("attrValueList");
        BaseAttrInfo baseAttrInfo = new BaseAttrInfo();
        baseAttrInfo.setAttrName(attrName);
        baseAttrInfo.setCategoryId(categoryId);
        int insert = baseAttrInfoMapper.insert(baseAttrInfo);
        if (insert > 0 && attrValueList != null) {
            Long id = baseAttrInfo.getId();
            ArrayList<BaseAttrValue> values = new ArrayList<>();
            attrValueList.forEach(valueName -> {
                Map map = (HashMap) valueName;
                String name = (String) map.get("valueName");
                if (StringUtils.isEmpty(name)) {
                    throw new GmallException("参数错误", 200);
                }
                BaseAttrValue baseAttrValue = new BaseAttrValue();
                baseAttrValue.setValueName(name);
                baseAttrValue.setAttrId(id);
                values.add(baseAttrValue);
            });
            baseAttrValueMapper.insertValues(values);
        }

    }

    /**
     * 获取平台属性
     *
     * @param category3Id
     * @return
     */
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category3Id) {
        return baseAttrInfoMapper.selectAttrAndValus(category3Id);
    }


    /**
     * 根据平台属性id获取平台属性和属性值
     *
     * @param id
     * @return
     */
    @Override
    public BaseAttrInfo getAttrValueListById(Long id) {

        if (StringUtils.isEmpty(id)) {
            throw new GmallException("参数错误", 200);
        }
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(id);
        if (baseAttrInfo == null) {
            return null;
        }
        LambdaQueryWrapper<BaseAttrValue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseAttrValue::getAttrId, id);
        List<BaseAttrValue> attrValues = baseAttrValueMapper.selectList(wrapper);
        baseAttrInfo.setAttrValueList(attrValues);
        return baseAttrInfo;
    }

    /**
     * 获取spu分页列表
     *
     * @param page
     * @param limit
     * @param category3Id
     * @return 分页公式 limit (curPage-1)*pageSize,pageSize   当前页curPage 每页多少条pageSize
     */
    @Override
    public Page getSpuPage(Long page, Long limit, Long category3Id) {
        if (page == null || page < 0) {
            page = 1L;
        }
        if (limit == null || limit < 0 || limit > 100) {
            limit = 10L;
        }
        //总条数
        LambdaQueryWrapper<SpuInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpuInfo::getCategory3Id, category3Id);
        Integer totalSize = spuInfoMapper.selectCount(wrapper);

        Integer pageBegin = Math.toIntExact((page - 1) * limit);
        List<SpuInfo> spuInfoList = spuInfoMapper.selectSpuInfoPage(pageBegin, limit, category3Id);

        Page<SpuInfo> spuInfoPage = new Page<>();
        spuInfoPage.setCurrent(pageBegin);
        spuInfoPage.setSize(limit);
        spuInfoPage.setTotal(totalSize);
        spuInfoPage.setRecords(spuInfoList);

        return spuInfoPage;
    }

    /**
     * 获取商品品牌
     *
     * @return
     */
    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    /**
     * 获取销售属性
     *
     * @return
     */
    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    /**
     * 保存spuInfo
     *
     * @param spuInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        //操作四张表  spu_info  spu_sale_attr  spu_image  spu_sale_attr_value
        /**
         * 新增和更新同一接口  有id update  无 id save
         * 1,保存 spu_info  得到spu id
         * 2,保存 spu_sale_attr spu_image spu_sale_attr_value
         */
        if (spuInfo.getId() != null) {
            //更新spuInfo
            int i = spuInfoMapper.updateById(spuInfo);
            if (i < 0) {
                throw new RuntimeException("更新失败,请稍后再试");
            }
            //删除  spu_image
            LambdaQueryWrapper<SpuImage> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SpuImage::getSpuId, spuInfo.getId());
            int a = spuImageMapper.delete(wrapper);
            //删除 spu_sale_attr  spu_sale_attr_value
            LambdaQueryWrapper<SpuSaleAttr> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(SpuSaleAttr::getSpuId, spuInfo.getId());
            int b = spuSaleAttrMapper.delete(wrapper2);
            //删除 spu_sale_attr_value
            LambdaQueryWrapper<SpuSaleAttrValue> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.eq(SpuSaleAttrValue::getSpuId, spuInfo.getId());
            int c = spuSaleAttrValueMapper.delete(wrapper3);
            if (a == 0 || b == 0 || c == 0) {
                throw new RuntimeException("更新失败,请稍后再试");
            }
        } else {
            int insert = spuInfoMapper.insert(spuInfo);
            if (insert <= 0) {
                throw new RuntimeException("保存失败,请稍后再试");
            }
        }


        Long spuInfoId = spuInfo.getId();

        //保存spu图片
        saveSpuImages(spuInfo, spuInfoId);
        //保存spuSaleAttr
        saveSpuSaleAttr(spuInfo, spuInfoId);

    }

    /**
     * 保存spuSaleAttr
     *
     * @param spuInfo
     * @param spuInfoId
     */
    private void saveSpuSaleAttr(SpuInfo spuInfo, Long spuInfoId) {
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (spuSaleAttrList.size() > 0) {
            spuSaleAttrList.forEach(s -> {
                s.setSpuId(spuInfoId);
            });
            int i = spuSaleAttrMapper.saveSpuSaleAttr(spuSaleAttrList);
            if (i <= 0) {
                throw new RuntimeException("保存失败,请稍后再试");
            }
        }
        //保存 spu_sale_attr_value
        saveSpuSaleAttrValue(spuSaleAttrList, spuInfoId);
    }

    /**
     * 保存 spu_sale_attr_value
     *
     * @param spuSaleAttrList
     * @param spuInfoId
     */
    private void saveSpuSaleAttrValue(List<SpuSaleAttr> spuSaleAttrList, Long spuInfoId) {
        if (spuSaleAttrList.size() == 0) {
            return;
        }

        spuSaleAttrList.forEach(spuSaleAttr -> {
            List<SpuSaleAttrValue> spuSaleAttrValueList =
                    spuSaleAttr.getSpuSaleAttrValueList();
            if (spuSaleAttrValueList.size() == 0) {
                return;
            }
            spuSaleAttrValueList.forEach(
                    spuSaleAttrValue -> {
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValue.setSpuId(spuInfoId);
                    }
            );
            spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                int insert1 = spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                if (insert1 <= 0) {
                    throw new RuntimeException("保存失败,请稍后再试");
                }
            });
        });
    }

    /**
     * 保存spu图片
     *
     * @param spuInfo
     * @param spuInfoId
     */
    private void saveSpuImages(SpuInfo spuInfo, Long spuInfoId) {
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (spuImageList.size() > 0) {
            spuImageList.forEach(spuImage -> spuImage.setSpuId(spuInfoId));
            int i = spuImageMapper.saveSpuImages(spuImageList);
            if (i <= 0) {
                throw new RuntimeException("保存失败,请稍后再试");
            }
        }
    }

    /**
     * 通过spuId查询 SpuSaleAttr
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> getSpuSaleAttr(Long spuId) {
        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.selectBySpuId(spuId);
        return spuSaleAttrList;
    }

    /**
     * 通过spuId查询 SpuImage
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuImage> getSpuImageListBy(Long spuId) {
        LambdaQueryWrapper<SpuImage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpuImage::getSpuId, spuId);
        return spuImageMapper.selectList(wrapper);
    }

    /**
     * 保存sku
     *
     * @param skuInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {

        /**
         * 一共四张表 sku_info sku_image sku_sale_attr_value  sku_attr_value(和平台属性中间关系表)
         */
        //保存 sku_info
        if (skuInfo == null) {
            throw new RuntimeException("参数错误");
        }
        int insert = skuInfoMapper.insert(skuInfo);
        if (insert <= 0) {
            throw new RuntimeException("保存失败,请稍后再试");
        }
        //保存 sku_image
        Long skuId = skuInfo.getId();
        saveSkuImage(skuInfo, skuId);
        //保存 sku_sale_attr_value
        saveSkuSaleAttrValue(skuInfo, skuId);
        //保存sku_attr_value(和平台属性中间关系表)
        saveSkuAttrValue(skuInfo, skuId);

        //TODO  调用web-all微服务 生成静态页面保存
        // 但是不发布 用Mq做，不用feign 最终生成就好

    }

    /**
     * //保存sku_attr_value(和平台属性中间关系表)
     *
     * @param skuInfo
     * @param skuId
     */
    private void saveSkuAttrValue(SkuInfo skuInfo, Long skuId) {
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuId);
            int insert1 = skuAttrValueMapper.insert(skuAttrValue);
            if (insert1 <= 0) {
                throw new RuntimeException("保存失败,请稍后再试");
            }
        });
    }

    /**
     * //保存 sku_sale_attr_value
     *
     * @param skuInfo
     * @param skuId
     */
    private void saveSkuSaleAttrValue(SkuInfo skuInfo, Long skuId) {
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            skuSaleAttrValue.setSkuId(skuId);
            int insert1 = skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            if (insert1 <= 0) {
                throw new RuntimeException("保存失败,请稍后再试");
            }
        });
    }

    /**
     * 保存 sku_image
     *
     * @param skuInfo
     * @param skuId
     */
    private void saveSkuImage(SkuInfo skuInfo, Long skuId) {
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> skuImage.setSkuId(skuId));
        int i = skuImageMapper.saveSkuImages(skuImageList);
        if (i <= 0) {
            throw new RuntimeException("保存失败,请稍后再试");
        }
    }

    /**
     * skuInfo分页查询
     *
     * @param page
     * @param limit
     * @return
     */
    @Override
    public IPage getSkuInfoPage(Long page, Long limit) {
        Page<SkuInfo> skuInfoPage = new Page<>(page, limit);
        IPage<SkuInfo> infoIPage = skuInfoMapper.selectPage(skuInfoPage, null);
        return infoIPage;
    }

    /**
     * 上下架商品
     *
     * @param skuId
     * @param mark
     */
    @Override
    public void upOrDown(Long skuId, Short mark) {
        if (skuId == null) {
            throw new RuntimeException("参数错误");
        }
        int i = skuInfoMapper.updateSaleState(skuId, mark);

        //TODO  上架 ：将商品的静态页面发布到nginx的映射目录
        //TODO  下架架 ：将nginx的映射目录的商品静态页面删除
        if (i <= 0) {
            throw new RuntimeException("上下架失败");
        }
    }
}
